import axios from 'axios';
import qs from 'qs';

const R = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    appid: 'jimu',
  },
});

/**
 * 请求拦截器
 */
R.interceptors.request.use((_) => {
  const config = _;
  const IS_GET = config.method === 'get';
  const data = (IS_GET ? config.params : config.data) || {};

  if (!config.headers['Authorization'] && window.localStorage.getItem('token')) {
    config.headers['Authorization'] = window.localStorage.getItem('token');
  }

  if (IS_GET) {
    data['_t'] = Date.now();
    config.params = data;
  } else if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
    config.data = qs.stringify(data);
  }

  return {
    ...config,
  };
});

/**
 * 响应拦截器
 */
R.interceptors.response.use(
  (response) => {
    if (
      response.data &&
      (typeof response.data.data !== 'undefined' || response.data.data != null)
    ) {
      return Promise.resolve(response.data.data);
    }
  },
  (error) => {
    if (error && error.response) {
      console.log(error.response.statusText);
    }
    console.error(error);
    return Promise.reject((error.response && error.response.data) || {});
  },
);

export default R;
